package tt.dz.appserver.dao.base;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 静态化HTML使用的类 后台系统用不上
 * @author 谢龙飞
 *
 */
@Repository(value="staticHtml")
public class StaticHtml {

	/**freemarker配置*/
	@Resource(name="freemarkerConfig")
	private FreeMarkerConfig freemarkerConfig;
	
	/**
	 * 静态化页面
	 * @param templateName 模板名称
	 * @param fileName 文件名称
	 * @param request httpservletrequest 对象
	 * @param rootMap 数据集
	 */
	public void staticHtml(String templateName, String fileName, HttpServletRequest request, Map<String, Object> rootMap) {
		
		//获取配置
		Configuration configuration = freemarkerConfig.getConfiguration();
		Writer out = null;
		try {
			//得到模板对象
			Template template = configuration.getTemplate("WEB-INF/tpl/"+templateName);
			File file = new File(request.getServletContext().getRealPath("/")+fileName);
			out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			
			//静态化
			rootMap.put("request", request);
			template.process(rootMap, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(out!=null){
				IOUtils.closeQuietly(out);
			}
		}
	}
	/**
	 * 文件是否存在
	 * @param rootPath
	 * @param fileName
	 * @return
	 */
	public boolean existsHtml(HttpServletRequest request, String fileName){
		File file = new File(request.getServletContext().getRealPath("/")+fileName);
		return file.exists();
	}
}
